package com.tuojiahr.common;

import java.util.List;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.tuojiahr.pagemodel.PageModel;
import com.tuojiahr.tools.PageUtil;

/**
 * 说明：
 *
 * @author wang.haibo
 * @date 2012-11-6 下午11:46:55
 */

public class HibernatePageCommon extends HibernateDaoSupport {

	public PageModel searchPaginated(String hql){
		return this.searchPaginated(hql, null, PageUtil.getOffset(), PageUtil.getPagesize());
	}
	
	public PageModel searchPaginated(String hql,Object param){
		return this.searchPaginated(hql, new Object[]{param}, PageUtil.getOffset(), PageUtil.getPagesize());
	}

	public PageModel searchPaginated(String hql,Object[] params){
		return this.searchPaginated(hql, params, PageUtil.getOffset(), PageUtil.getPagesize());
	}
	
	public PageModel searchPaginated(String hql,int offset,int pagesize){
		return this.searchPaginated(hql, null, offset, pagesize);
	}
	
	public PageModel searchPaginated(String hql,Object param,int offset,int pagesize){
		return this.searchPaginated(hql, new Object[]{param}, offset, pagesize);
	}
	
	/**
	 * 获取查询记录总数的HQL语句
	 * @param hql
	 * @return 查询记录总数的HQL语句
	 */
	private String getCountHql(String hql){
		//获得from在hql语句中出现的位置
		int index = hql.indexOf("from");
		
		//如果hql语句中包含from，则拼接出查询记录总数的语句
		if(-1 != index){
			return "select count(*)" + hql.substring(index);
		}
		throw new RuntimeException("不合法的Hql语句");
	}
	
	/**
	 * 获取分页模型
	 * @param hql
	 * @param params 拼接HQL语句的参数
	 * @param offset 分页偏移量
	 * @param pagesize 每页的记录数
	 * @return
	 */
	public PageModel searchPaginated(String hql,Object[] params,int offset,int pagesize){
		
		//查询总的记录数
		String countHql = this.getCountHql(hql);
		Query query = this.getSession().createQuery(countHql);
		if(null != query && null != params && params.length > 0){
			int count = 0;
			for(int i = 0; i < params.length; ++ i){
				if(-1 != hql.indexOf("like") && 0 == count) {
					//拼装模糊查询语句
					query.setParameter(i, "%" + params[i] + "%");
					count = 1;
				} else {
					query.setParameter(i, params[i]);
				}
			}
		}
		int total = ((Long)query.uniqueResult()).intValue();
		
		//查询记录列表
		query = this.getSession().createQuery(hql);
		if(null != query && null != params && params.length > 0){
			int count = 0;
			for(int i = 0; i < params.length; ++i){
				if(-1 != hql.indexOf("like") && 0 == count) {
					//拼装模糊查询语句
					query.setParameter(i, "%" + params[i] + "%");
					count = 1;
				} else {
					query.setParameter(i, params[i]);
				}
			}		
		}
		query.setFirstResult(offset);
		query.setMaxResults(pagesize);
		List<?> list = query.list();
		
		PageModel pageModel = new PageModel();
		pageModel.setTotal(total);
		pageModel.setList(list);
		
		return pageModel;
	}
}
